package com.kai.mqtt.util;


/**
 * @author weijk
 * @since 2024/6/10
 */
public class TopicUtil {

    private static final String SHARE_TOPIC_PREFIX = "$share/";

    private static final char SLASH = '/';

    private static final char HASHTAG = '#';

    private static final char PLUS = '+';

    public static boolean isShareTopic(String topic) {
        return topic.startsWith(SHARE_TOPIC_PREFIX);
    }

    public static boolean shareMatch(String topicFilter, String topic) {
        int topicFilterIndex = 7;
        while (topicFilter.charAt(topicFilterIndex) != SLASH) {
            topicFilterIndex++;
        }

        return match(++topicFilterIndex, topicFilter, topic);
    }

    public static boolean match(String topicFilter, String topic) {
        return match(0, topicFilter, topic);
    }

    public static boolean match(int topicFilterIndex, String topicFilter, String topic) {
        int topicIndex = 0;
        for (; topicFilterIndex < topicFilter.length(); topicFilterIndex++, topicIndex++) {
            char ch = topicFilter.charAt(topicFilterIndex);
            if (ch == HASHTAG) {
                return true;
            } else if (ch == PLUS) {
                if (topic.charAt(topicIndex) == HASHTAG) {
                    return false;
                }
                while (true) {
                    if (topicIndex == topic.length()) {
                        return topicFilterIndex == topicFilter.length() - 1;
                    } else if (topic.charAt(topicIndex) == SLASH) {
                        topicFilterIndex++;
                        break;
                    } else {
                        topicIndex++;
                    }
                }
            } else if (topicIndex == topic.length() || ch != topic.charAt(topicIndex)) {
                return false;
            }
        }

        return topicIndex == topic.length();
    }
}